package com.xingxue.module.user.controller;

import com.xingxue.module.user.entity.*;
import com.xingxue.module.user.repository.ReplyRepository;
import com.xingxue.module.user.repository.ReplyThumbsRepository;
import com.xingxue.module.user.repository.UserRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 回复api
 *
 * @author yihang
 */
@RestController
public class ReplyController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ReplyRepository replyRepository;

    @Autowired
    private ReplyThumbsRepository replyThumbsRepository;

    /**
     * 根据题目编号查询它所有的回复信息
     *
     * @param questionId   题目编号
     * @return 回复信息
     */
    @GetMapping("/api/reply")
    @ApiOperation(value = "根据多个题目编号查询它所有的回复信息", httpMethod = "GET", produces = "application/json")
    public ReplyResult findByQuestionIds(@RequestParam @ApiParam(value = "题目编号", required = true) List<Integer> questionId) {
        List<Reply> all = replyRepository.findByQuestionIdIn(questionId);
        Map<Integer, List<Reply>> topMap = new LinkedHashMap<>();
        Set<Integer> userIds = new HashSet<>();
        HashMap<Integer, Reply> map = new HashMap<>();
        for(Reply r: all) {
            List<Reply> top = topMap.computeIfAbsent(r.getQuestionId(), (x) -> new ArrayList<>());
            if (r.getPid() == 0) {
                top.add(r);
            }
            map.put(r.getId(), r);
            userIds.add(r.getUserId());
        }


        Map<Integer, User> userMap = userRepository.findAll(userIds)
                .stream().collect(Collectors.toMap(User::getId, user -> user));
        for (Reply r : all) {
            Reply parent = map.get(r.getPid());
            if (parent != null) {
                parent.getChildren().add(r);
            }
            r.setUser(userMap.get(r.getUserId()));
        }
        return new ReplyResult(true, "查询成功", topMap);
    }

    @PostMapping("api/reply/{replyId}/{userId}/thumbsUp")
    @ApiOperation(value = "回复信息点赞或取消点赞", httpMethod = "POST", produces = "application/json")
    public Result thumbsUp(@PathVariable @ApiParam(value = "回复编号", required = true) int replyId, @PathVariable @ApiParam(value = "用户编号", required = true) int userId) {
        return thumbs(true, replyId, userId);
    }

    @PostMapping("api/reply/{replyId}/{userId}/thumbsDown")
    @ApiOperation(value = "回复信息点差或取消点差", httpMethod = "POST", produces = "application/json")
    public Result thumbsDown(@PathVariable @ApiParam(value = "回复编号", required = true) int replyId, @ApiParam(value = "用户编号", required = true) @PathVariable int userId) {
        return thumbs(false, replyId, userId);
    }

    @Transactional
    protected Result thumbs(boolean up, int replyId, int userId) {
        Reply old = replyRepository.findOne(replyId);
        if (old == null) {
            return new Result(false, "该回复id不正确");
        }
        ReplyThumbs oldThumbs = replyThumbsRepository.findByUserIdAndReplyIdAndUp(userId, replyId, up);
        if(oldThumbs != null) {
            replyThumbsRepository.delete(oldThumbs);
        } else {
            ReplyThumbs thumbs = new ReplyThumbs();
            thumbs.setReplyId(replyId);
            thumbs.setUserId(userId);
            thumbs.setUp(up);
            replyThumbsRepository.save(thumbs);
        }
        if (up) {
            if(oldThumbs != null) {
                old.setThumbsUp(old.getThumbsUp() - 1);
                replyRepository.save(old);
                return new Result(true, "取消点赞成功");
            } else {
                old.setThumbsUp(old.getThumbsUp() + 1);
                replyRepository.save(old);
                return new Result(true, "点赞成功");
            }
        } else {
            if(oldThumbs != null) {
                old.setThumbsDown(old.getThumbsDown() - 1);
                replyRepository.save(old);
                return new Result(true, "取消点差成功");
            } else {
                old.setThumbsDown(old.getThumbsDown() + 1);
                replyRepository.save(old);
                return new Result(true, "点差成功");
            }
        }
    }

    /**
     * 添加或修改回复
     *
     * @param reply 回复信息
     * @return
     */
    @PostMapping("api/reply")
    @ApiOperation(value = "添加或修改回复", httpMethod = "POST", produces = "application/json", consumes = "application/json")
    public Result save(@RequestBody @ApiParam(value = "回复对象", required = true) Reply reply) {
        if (reply.getUserId() == null) {
            return new Result(false, "用户编号(userId)不能为空");
        }
        if (reply.getContent() == null || reply.getContent().trim().length() == 0) {
            return new Result(false, "该回复没有内容(content)");
        }
        if (reply.getQuestionId() == null) {
            return new Result(false, "该回复缺少(pid)");
        }
        if (reply.getPid() > 0) {
            User parent = userRepository.findOne(reply.getPid());
            if (parent == null) {
                return new Result(false, "该回复有父编号(pid)但父编号非法");
            }
        }
        if (reply.getId() != null) {
            Reply old = replyRepository.findOne(reply.getId());
            if (old != null) {
                old.setUserId(reply.getUserId());
                old.setContent(reply.getContent());
                old.setPid(reply.getPid());
                old.setQuestionId(reply.getQuestionId());
                replyRepository.save(old);
                return new Result(true, "修改回复成功");
            }
        }
        replyRepository.save(reply);
        return new Result(true, "新增回复成功");
    }


}
